﻿using IBLL;
using MODEL;
using SysCommon;
using SysHelper.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;

namespace SysHelper
{
    public partial class OperateContext
    {
        HttpContext httpContext { get { return HttpContext.Current; } }

        HttpRequest Request { get { return httpContext.Request; } }

        HttpResponse Response { get { return httpContext.Response; } }

        HttpSessionState Session { get { return httpContext.Session; } }
    }

    public partial class OperateContext
    {
        #region 通过构造函数实例化 业务仓储    BllSession

        public IBLLSession BllSession;

        public OperateContext()
        {
            BllSession = DI.Spring.GetObject<IBLLSession>("BLLSession");
        }
        #endregion
    }

    public partial class OperateContext
    {
        #region 获取当前 操作上下文  OperateContext CurrentContext
        public static OperateContext CurrentContext
        {
            get
            {
                OperateContext context = CallContext.GetData(typeof(OperateContext).Name) as OperateContext;
                if (context == null)
                {
                    context = new OperateContext();
                    CallContext.SetData(typeof(OperateContext).Name, context);
                }
                return context;
            }
        }

        #endregion
    }

    public partial class OperateContext
    {
        const string UsrCookiePath = "/";
        const string InfoKey = "usr";
        const string UsrPermissionKey = "usrpermission";

        #region 当前用户 LoginAccountInfo User
        /// <summary>
        /// 当前用户  
        /// </summary>
        public LoginAccountInfo User
        {
            get
            {
                return Session[InfoKey] as LoginAccountInfo;
            }
            set
            {
                Session[InfoKey] = value;
            }
        }
        #endregion
         
        #region 登陆 +bool Login(LoginUser user)
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool Login(LoginUser user)
        {
            LoginAccountInfo usr = this.BllSession.ILoginAccountInfo_BLL.GetListByWhere(s => s.LoginAccount == user.LoginAccount && s.LoginPassword == user.LoginPassword).FirstOrDefault();
            if (usr != null)
            {
                User = usr;
                if (user.Remember)
                {
                    string strCookieValue = SecurityHelper.EncryptUserInfo(usr.LoginAccountInfoID.ToString());
                    HttpCookie cookie = new HttpCookie(InfoKey, strCookieValue);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    cookie.Path = UsrCookiePath;
                    Response.Cookies.Add(cookie);
                }
                Permission = GetUserPermission(usr.LoginAccountInfoID);
                return true;
            }
            return false;
        }
        #endregion

        #region 判断是否登陆 +bool IsLogin()
        /// <summary>
        /// 判断是否登陆
        /// </summary>
        /// <returns></returns>
        public bool IsLogin()
        {
            //1.验证用户是否登陆(Session && Cookie)
            if (Session[InfoKey] == null)
            {
                if (Request.Cookies[InfoKey] == null)
                {
                    return false;
                }
                else
                {
                    string strUserInfo = Request.Cookies[InfoKey].Value;
                    strUserInfo = SecurityHelper.DecryptUserInfo(strUserInfo);
                    int userId = int.Parse(strUserInfo);
                    MODEL.LoginAccountInfo usr = this.BllSession.ILoginAccountInfo_BLL.GetListByWhere(s => s.IsDel == false && s.LoginAccountInfoID == userId).First();
                    User = usr;
                    Permission = OperateContext.CurrentContext.GetUserPermission(usr.LoginAccountInfoID);
                }
            }
            return true;
        }
        #endregion


        #region  当前用户权限 +List<View_Permission> Permission
        // <summary>
        /// 当前用户权限
        /// </summary>
        public List<View_Permission> Permission
        {
            get
            {
                return Session[UsrPermissionKey] as List<View_Permission>;
            }
            set
            {
                Session[UsrPermissionKey] = value;
            }
        }
        #endregion

        #region 获取用户权限 +List<View_Permission> GetUserPermission(int usrId)
        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="usrId"></param>
        /// <returns></returns>
        public List<View_Permission> GetUserPermission(int usrId)
        {

            return new List<View_Permission>();
        } 
        #endregion

        #region 判断是否有权限 +IsPemission(string areaName, string controllerName, string actionName, string httpMethod)
        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <param name="httpMethod"></param>
        /// <returns></returns>
        public bool IsPemission(string areaName, string controllerName, string actionName, string httpMethod)
        {
            var listP = from per in Permission
                        where
                            (string.Equals(per.Area, areaName, StringComparison.CurrentCultureIgnoreCase) || areaName == "home") &&
                            string.Equals(per.Controller, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                            string.Equals(per.Action, actionName, StringComparison.CurrentCultureIgnoreCase) &&
                                (per.Method == -1 || per.Method == (httpMethod.ToLower() == "get" ? 0 : 1)
                            )
                        select per;
            return listP.Count() > 0; 
        }
        #endregion

        #region 菜单 List<View_DsSystemMenu> MenuList
        /// <summary>
        /// 菜单 List<View_DsSystemMenu> MenuList
        /// </summary>
        private List<View_DsSystemMenu> _MenuList;
        public List<View_DsSystemMenu> MenuList
        {
            get
            {
                if (_MenuList == null || _MenuList.Count() < 1)
                {
                    _MenuList = this.BllSession.IView_DsSystemMenu_BLL.GetListByWhere(s => s.DsSystemID == 1 && s.IsDel == false);
                }
                return _MenuList;
            }
        }
        #endregion



        #region 生成 Json 格式的返回值 + RedirectAjax(AjaxMsgStatuEnum statu, string msg = null, object data = null, string backurl = null)
        /// <summary>
        /// 生成 Json 格式的返回值
        /// </summary>
        /// <param name="statu"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <param name="backurl"></param>
        /// <returns></returns>
        public ActionResult RedirectAjax(AjaxMsgStatuEnum statu, string msg = null, object data = null, string backurl = null)
        {
            return new JsonResult()
                    {
                        Data = new AjaxMsgModel() { Statu = statu.ToString(), Msg = msg, Data = data, BackUrl = backurl },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
        }
        #endregion
         
        #region 重定向方法 根据Action方法特性  +ActionResult Redirect(string url, ActionDescriptor action)
        /// <summary>
        /// 重定向方法 有两种情况：如果是Ajax请求，则返回 Json字符串；如果是普通请求，则 返回重定向命令
        /// </summary>
        /// <returns></returns>
        public ActionResult Redirect(string url, ActionDescriptor action)
        {
            //如果Ajax请求没有权限，就返回 Json消息
            if (action.IsDefined(typeof(AjaxRequestAttribute), false) || action.ControllerDescriptor.IsDefined(typeof(AjaxRequestAttribute), false))
            {
                return RedirectAjax(AjaxMsgStatuEnum.NoLogin, "您没有登陆或权限访问此页面", null, url);
            }
            else//如果 超链接或表单 没有权限访问，则返回 302重定向命令
            {
                return new RedirectResult(url); 
            }
        }
        #endregion

        public ActionResult  JavaScript(string script)
        {
            return new JavaScriptResult()
            {
                Script = script
            };
        }
    }

}
